
<!DOCTYPE HTML>
<html lang="" >
    <head>
        <meta charset="UTF-8">
        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
        <title>Writing Tests · GitBook</title>
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="description" content="">
        <meta name="generator" content="GitBook 3.2.2">
        
        
        
    
    <link rel="stylesheet" href="../gitbook/style.css">

    
            
                
                <link rel="stylesheet" href="../gitbook/gitbook-plugin-highlight/website.css">
                
            
                
                <link rel="stylesheet" href="../gitbook/gitbook-plugin-search/search.css">
                
            
                
                <link rel="stylesheet" href="../gitbook/gitbook-plugin-fontsettings/website.css">
                
            
        

    

    
        
    
        
    
        
    
        
    
        
    
        
    

        
    
    
    <meta name="HandheldFriendly" content="true"/>
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <link rel="apple-touch-icon-precomposed" sizes="152x152" href="../gitbook/images/apple-touch-icon-precomposed-152.png">
    <link rel="shortcut icon" href="../gitbook/images/favicon.ico" type="image/x-icon">

    
    <link rel="next" href="ComputingDerivedData.html" />
    
    
    <link rel="prev" href="ServerRendering.html" />
    

    </head>
    <body>
        
<div class="book">
    <div class="book-summary">
        
            
<div id="book-search-input" role="search">
    <input type="text" placeholder="Type to search" />
</div>

            
                <nav role="navigation">
                


<ul class="summary">
    
    

    

    
        
        
    
        <li class="chapter " data-level="1.1" data-path="../">
            
                <a href="../">
            
                    
                    Read Me
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.2" data-path="../introduction/">
            
                <a href="../introduction/">
            
                    
                    Introduction
            
                </a>
            

            
            <ul class="articles">
                
    
        <li class="chapter " data-level="1.2.1" data-path="../introduction/Motivation.html">
            
                <a href="../introduction/Motivation.html">
            
                    
                    Motivation
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.2.2" data-path="../introduction/CoreConcepts.html">
            
                <a href="../introduction/CoreConcepts.html">
            
                    
                    Core Concepts
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.2.3" data-path="../introduction/ThreePrinciples.html">
            
                <a href="../introduction/ThreePrinciples.html">
            
                    
                    Three Principles
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.2.4" data-path="../introduction/PriorArt.html">
            
                <a href="../introduction/PriorArt.html">
            
                    
                    Prior Art
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.2.5" data-path="../introduction/Ecosystem.html">
            
                <a href="../introduction/Ecosystem.html">
            
                    
                    Ecosystem
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.2.6" data-path="../introduction/Examples.html">
            
                <a href="../introduction/Examples.html">
            
                    
                    Examples
            
                </a>
            

            
        </li>
    

            </ul>
            
        </li>
    
        <li class="chapter " data-level="1.3" data-path="../basics/">
            
                <a href="../basics/">
            
                    
                    Basics
            
                </a>
            

            
            <ul class="articles">
                
    
        <li class="chapter " data-level="1.3.1" data-path="../basics/Actions.html">
            
                <a href="../basics/Actions.html">
            
                    
                    Actions
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.3.2" data-path="../basics/Reducers.html">
            
                <a href="../basics/Reducers.html">
            
                    
                    Reducers
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.3.3" data-path="../basics/Store.html">
            
                <a href="../basics/Store.html">
            
                    
                    Store
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.3.4" data-path="../basics/DataFlow.html">
            
                <a href="../basics/DataFlow.html">
            
                    
                    Data Flow
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.3.5" data-path="../basics/UsageWithReact.html">
            
                <a href="../basics/UsageWithReact.html">
            
                    
                    Usage with React
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.3.6" data-path="../basics/ExampleTodoList.html">
            
                <a href="../basics/ExampleTodoList.html">
            
                    
                    Example: Todo List
            
                </a>
            

            
        </li>
    

            </ul>
            
        </li>
    
        <li class="chapter " data-level="1.4" data-path="../advanced/">
            
                <a href="../advanced/">
            
                    
                    Advanced
            
                </a>
            

            
            <ul class="articles">
                
    
        <li class="chapter " data-level="1.4.1" data-path="../advanced/AsyncActions.html">
            
                <a href="../advanced/AsyncActions.html">
            
                    
                    Async Actions
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.4.2" data-path="../advanced/AsyncFlow.html">
            
                <a href="../advanced/AsyncFlow.html">
            
                    
                    Async Flow
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.4.3" data-path="../advanced/Middleware.html">
            
                <a href="../advanced/Middleware.html">
            
                    
                    Middleware
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.4.4" data-path="../advanced/UsageWithReactRouter.html">
            
                <a href="../advanced/UsageWithReactRouter.html">
            
                    
                    Usage with React Router
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.4.5" data-path="../advanced/ExampleRedditAPI.html">
            
                <a href="../advanced/ExampleRedditAPI.html">
            
                    
                    Example: Reddit API
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.4.6" >
            
                <span>
            
                    
                    Next Steps
            
                </span>
            

            
        </li>
    

            </ul>
            
        </li>
    
        <li class="chapter " data-level="1.5" data-path="./">
            
                <a href="./">
            
                    
                    Recipes
            
                </a>
            

            
            <ul class="articles">
                
    
        <li class="chapter " data-level="1.5.1" data-path="MigratingToRedux.html">
            
                <a href="MigratingToRedux.html">
            
                    
                    Migrating to Redux
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.2" data-path="UsingObjectSpreadOperator.html">
            
                <a href="UsingObjectSpreadOperator.html">
            
                    
                    Using Object Spread Operator
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.3" data-path="ReducingBoilerplate.html">
            
                <a href="ReducingBoilerplate.html">
            
                    
                    Reducing Boilerplate
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.4" data-path="ServerRendering.html">
            
                <a href="ServerRendering.html">
            
                    
                    Server Rendering
            
                </a>
            

            
        </li>
    
        <li class="chapter active" data-level="1.5.5" data-path="WritingTests.html">
            
                <a href="WritingTests.html">
            
                    
                    Writing Tests
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.6" data-path="ComputingDerivedData.html">
            
                <a href="ComputingDerivedData.html">
            
                    
                    Computing Derived Data
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.7" data-path="ImplementingUndoHistory.html">
            
                <a href="ImplementingUndoHistory.html">
            
                    
                    Implementing Undo History
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.8" data-path="IsolatingSubapps.html">
            
                <a href="IsolatingSubapps.html">
            
                    
                    Isolating Subapps
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.9" data-path="StructuringReducers.html">
            
                <a href="StructuringReducers.html">
            
                    
                    Structuring Reducers
            
                </a>
            

            
            <ul class="articles">
                
    
        <li class="chapter " data-level="1.5.9.1" data-path="reducers/PrerequisiteConcepts.html">
            
                <a href="reducers/PrerequisiteConcepts.html">
            
                    
                    Prerequisite Concepts
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.9.2" data-path="reducers/BasicReducerStructure.html">
            
                <a href="reducers/BasicReducerStructure.html">
            
                    
                    Basic Reducer Structure
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.9.3" data-path="reducers/SplittingReducerLogic.html">
            
                <a href="reducers/SplittingReducerLogic.html">
            
                    
                    Splitting Reducer Logic
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.9.4" data-path="reducers/RefactoringReducersExample.html">
            
                <a href="reducers/RefactoringReducersExample.html">
            
                    
                    Refactoring Reducers Example
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.9.5" data-path="reducers/UsingCombineReducers.html">
            
                <a href="reducers/UsingCombineReducers.html">
            
                    
                    Using combineReducers
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.9.6" data-path="reducers/BeyondCombineReducers.html">
            
                <a href="reducers/BeyondCombineReducers.html">
            
                    
                    Beyond combineReducers
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.9.7" data-path="reducers/NormalizingStateShape.html">
            
                <a href="reducers/NormalizingStateShape.html">
            
                    
                    Normalizing State Shape
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.9.8" data-path="reducers/UpdatingNormalizedData.html">
            
                <a href="reducers/UpdatingNormalizedData.html">
            
                    
                    Updating Normalized Data
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.9.9" data-path="reducers/ReusingReducerLogic.html">
            
                <a href="reducers/ReusingReducerLogic.html">
            
                    
                    Reusing Reducer Logic
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.9.10" data-path="reducers/ImmutableUpdatePatterns.html">
            
                <a href="reducers/ImmutableUpdatePatterns.html">
            
                    
                    Immutable Update Patterns
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.5.9.11" data-path="reducers/InitializingState.html">
            
                <a href="reducers/InitializingState.html">
            
                    
                    Initializing State
            
                </a>
            

            
        </li>
    

            </ul>
            
        </li>
    
        <li class="chapter " data-level="1.5.10" data-path="UsingImmutableJS.html">
            
                <a href="UsingImmutableJS.html">
            
                    
                    Using Immutable.JS with Redux
            
                </a>
            

            
        </li>
    

            </ul>
            
        </li>
    
        <li class="chapter " data-level="1.6" data-path="../FAQ.html">
            
                <a href="../FAQ.html">
            
                    
                    FAQ
            
                </a>
            

            
            <ul class="articles">
                
    
        <li class="chapter " data-level="1.6.1" data-path="../faq/General.html">
            
                <a href="../faq/General.html">
            
                    
                    General
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.6.2" data-path="../faq/Reducers.html">
            
                <a href="../faq/Reducers.html">
            
                    
                    Reducers
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.6.3" data-path="../faq/OrganizingState.html">
            
                <a href="../faq/OrganizingState.html">
            
                    
                    Organizing State
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.6.4" data-path="../faq/StoreSetup.html">
            
                <a href="../faq/StoreSetup.html">
            
                    
                    Store Setup
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.6.5" data-path="../faq/Actions.html">
            
                <a href="../faq/Actions.html">
            
                    
                    Actions
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.6.6" data-path="../faq/ImmutableData.html">
            
                <a href="../faq/ImmutableData.html">
            
                    
                    Immutable Data
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.6.7" data-path="../faq/CodeStructure.html">
            
                <a href="../faq/CodeStructure.html">
            
                    
                    Code Structure
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.6.8" data-path="../faq/Performance.html">
            
                <a href="../faq/Performance.html">
            
                    
                    Performance
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.6.9" data-path="../faq/ReactRedux.html">
            
                <a href="../faq/ReactRedux.html">
            
                    
                    React Redux
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.6.10" data-path="../faq/Miscellaneous.html">
            
                <a href="../faq/Miscellaneous.html">
            
                    
                    Miscellaneous
            
                </a>
            

            
        </li>
    

            </ul>
            
        </li>
    
        <li class="chapter " data-level="1.7" data-path="../Troubleshooting.html">
            
                <a href="../Troubleshooting.html">
            
                    
                    Troubleshooting
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.8" data-path="../Glossary.html">
            
                <a href="../Glossary.html">
            
                    
                    Glossary
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.9" data-path="../api/">
            
                <a href="../api/">
            
                    
                    API Reference
            
                </a>
            

            
            <ul class="articles">
                
    
        <li class="chapter " data-level="1.9.1" data-path="../api/createStore.html">
            
                <a href="../api/createStore.html">
            
                    
                    createStore
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.9.2" data-path="../api/Store.html">
            
                <a href="../api/Store.html">
            
                    
                    Store
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.9.3" data-path="../api/combineReducers.html">
            
                <a href="../api/combineReducers.html">
            
                    
                    combineReducers
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.9.4" data-path="../api/applyMiddleware.html">
            
                <a href="../api/applyMiddleware.html">
            
                    
                    applyMiddleware
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.9.5" data-path="../api/bindActionCreators.html">
            
                <a href="../api/bindActionCreators.html">
            
                    
                    bindActionCreators
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.9.6" data-path="../api/compose.html">
            
                <a href="../api/compose.html">
            
                    
                    compose
            
                </a>
            

            
        </li>
    

            </ul>
            
        </li>
    
        <li class="chapter " data-level="1.10" data-path="../CHANGELOG.md">
            
                <span>
            
                    
                    Change Log
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.11" data-path="../PATRONS.md">
            
                <span>
            
                    
                    Patrons
            
                </a>
            

            
        </li>
    
        <li class="chapter " data-level="1.12" data-path="../Feedback.html">
            
                <a href="../Feedback.html">
            
                    
                    Feedback
            
                </a>
            

            
        </li>
    

    

    <li class="divider"></li>

    <li>
        <a href="https://www.gitbook.com" target="blank" class="gitbook-link">
            Published with GitBook
        </a>
    </li>
</ul>


                </nav>
            
        
    </div>

    <div class="book-body">
        
            <div class="body-inner">
                
                    

<div class="book-header" role="navigation">
    

    <!-- Title -->
    <h1>
        <i class="fa fa-circle-o-notch fa-spin"></i>
        <a href=".." >Writing Tests</a>
    </h1>
</div>




                    <div class="page-wrapper" tabindex="-1" role="main">
                        <div class="page-inner">
                            
<div id="book-search-results">
    <div class="search-noresults">
    
                                <section class="normal markdown-section">
                                
                                <h1 id="writing-tests">Writing Tests</h1>
<p>Because most of the Redux code you write are functions, and many of them are pure, they are easy to test without mocking.</p>
<h3 id="setting-up">Setting Up</h3>
<p>We recommend <a href="http://facebook.github.io/jest/" target="_blank">Jest</a> as the testing engine.
Note that it runs in a Node environment, so you won&apos;t have access to the DOM.</p>
<pre><code>npm install --save-dev jest
</code></pre><p>To use it together with <a href="http://babeljs.io" target="_blank">Babel</a>, you will need to install <code>babel-jest</code>:</p>
<pre><code class="lang-js">npm install --save-dev babel-jest
</code></pre>
<p>and configure it to use ES2015 features in <code>.babelrc</code>:</p>
<pre><code class="lang-js">{
  <span class="hljs-string">&quot;presets&quot;</span>: [<span class="hljs-string">&quot;es2015&quot;</span>]
}
</code></pre>
<p>Then, add this to <code>scripts</code> in your <code>package.json</code>:</p>
<pre><code class="lang-js">{
  ...
  <span class="hljs-string">&quot;scripts&quot;</span>: {
    ...
    <span class="hljs-string">&quot;test&quot;</span>: <span class="hljs-string">&quot;jest&quot;</span>,
    <span class="hljs-string">&quot;test:watch&quot;</span>: <span class="hljs-string">&quot;npm test -- --watch&quot;</span>
  },
  ...
}
</code></pre>
<p>and run <code>npm test</code> to run it once, or <code>npm run test:watch</code> to test on every file change.</p>
<h3 id="action-creators">Action Creators</h3>
<p>In Redux, <a href="../Glossary.html#action" class="glossary-term" title="">action</a> creators are functions which return plain objects. When testing <a href="../Glossary.html#action" class="glossary-term" title="">action</a> creators we want to test whether the correct <a href="../Glossary.html#action" class="glossary-term" title="">action</a> creator was called and also whether the right <a href="../Glossary.html#action" class="glossary-term" title="">action</a> was returned.</p>
<h4 id="example">Example</h4>
<pre><code class="lang-js"><span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addTodo</span>(<span class="hljs-params">text</span>) </span>{
  <span class="hljs-keyword">return</span> {
    type: <span class="hljs-string">&apos;ADD_TODO&apos;</span>,
    text
  }
}
</code></pre>
<p>can be tested like:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> actions <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;../../actions/TodoActions&apos;</span>
<span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> types <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;../../constants/ActionTypes&apos;</span>

describe(<span class="hljs-string">&apos;actions&apos;</span>, () =&gt; {
  it(<span class="hljs-string">&apos;should create an action to add a todo&apos;</span>, () =&gt; {
    <span class="hljs-keyword">const</span> text = <span class="hljs-string">&apos;Finish docs&apos;</span>
    <span class="hljs-keyword">const</span> expectedAction = {
      type: types.ADD_TODO,
      text
    }
    expect(actions.addTodo(text)).toEqual(expectedAction)
  })
})
</code></pre>
<h3 id="async-action-creators">Async Action Creators</h3>
<p>For async <a href="../Glossary.html#action" class="glossary-term" title="">action</a> creators using <a href="https://github.com/gaearon/redux-thunk" target="_blank">Redux Thunk</a> or other <a href="../Glossary.html#middleware" class="glossary-term" title="">middleware</a>, it&apos;s best to completely mock the Redux <a href="../Glossary.html#store" class="glossary-term" title="">store</a> for tests. You can apply the <a href="../Glossary.html#middleware" class="glossary-term" title="">middleware</a> to a mock <a href="../Glossary.html#store" class="glossary-term" title="">store</a> using <a href="https://github.com/arnaudbenard/redux-mock-store" target="_blank">redux-mock-store</a>. You can also use <a href="https://github.com/pgte/nock" target="_blank">nock</a> to mock the HTTP requests.</p>
<h4 id="example">Example</h4>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> fetch <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;isomorphic-fetch&apos;</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchTodosRequest</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> {
    type: FETCH_TODOS_REQUEST
  }
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchTodosSuccess</span>(<span class="hljs-params">body</span>) </span>{
  <span class="hljs-keyword">return</span> {
    type: FETCH_TODOS_SUCCESS,
    body
  }
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchTodosFailure</span>(<span class="hljs-params">ex</span>) </span>{
  <span class="hljs-keyword">return</span> {
    type: FETCH_TODOS_FAILURE,
    ex
  }
}

<span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchTodos</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> dispatch =&gt; {
    dispatch(fetchTodosRequest())
    <span class="hljs-keyword">return</span> fetch(<span class="hljs-string">&apos;http://example.com/todos&apos;</span>)
      .then(res =&gt; res.json())
      .then(json =&gt; dispatch(fetchTodosSuccess(json.body)))
      .catch(ex =&gt; dispatch(fetchTodosFailure(ex)))
  }
}
</code></pre>
<p>can be tested like:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> configureMockStore <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;redux-mock-store&apos;</span>
<span class="hljs-keyword">import</span> thunk <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;redux-thunk&apos;</span>
<span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> actions <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;../../actions/TodoActions&apos;</span>
<span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> types <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;../../constants/ActionTypes&apos;</span>
<span class="hljs-keyword">import</span> nock <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;nock&apos;</span>
<span class="hljs-keyword">import</span> expect <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;expect&apos;</span> <span class="hljs-comment">// You can use any testing library</span>

<span class="hljs-keyword">const</span> middlewares = [ thunk ]
<span class="hljs-keyword">const</span> mockStore = configureMockStore(middlewares)

describe(<span class="hljs-string">&apos;async actions&apos;</span>, () =&gt; {
  afterEach(() =&gt; {
    nock.cleanAll()
  })

  it(<span class="hljs-string">&apos;creates FETCH_TODOS_SUCCESS when fetching todos has been done&apos;</span>, () =&gt; {
    nock(<span class="hljs-string">&apos;http://example.com/&apos;</span>)
      .get(<span class="hljs-string">&apos;/todos&apos;</span>)
      .reply(<span class="hljs-number">200</span>, { body: { todos: [<span class="hljs-string">&apos;do something&apos;</span>] }})

    <span class="hljs-keyword">const</span> expectedActions = [
      { type: types.FETCH_TODOS_REQUEST },
      { type: types.FETCH_TODOS_SUCCESS, body: { todos: [<span class="hljs-string">&apos;do something&apos;</span>]  } }
    ]
    <span class="hljs-keyword">const</span> store = mockStore({ todos: [] })

    <span class="hljs-keyword">return</span> store.dispatch(actions.fetchTodos())
      .then(() =&gt; { <span class="hljs-comment">// return of async actions</span>
        expect(store.getActions()).toEqual(expectedActions)
      })
  })
})
</code></pre>
<h3 id="reducers">Reducers</h3>
<p>A <a href="../Glossary.html#reducer" class="glossary-term" title="">reducer</a> should return the new <a href="../Glossary.html#state" class="glossary-term" title="">state</a> after applying the <a href="../Glossary.html#action" class="glossary-term" title="">action</a> to the previous <a href="../Glossary.html#state" class="glossary-term" title="">state</a>, and that&apos;s the behavior tested below.</p>
<h4 id="example">Example</h4>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { ADD_TODO } <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;../constants/ActionTypes&apos;</span>

<span class="hljs-keyword">const</span> initialState = [
  {
    text: <span class="hljs-string">&apos;Use Redux&apos;</span>,
    completed: <span class="hljs-literal">false</span>,
    id: <span class="hljs-number">0</span>
  }
]

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">todos</span>(<span class="hljs-params">state = initialState, action</span>) </span>{
  <span class="hljs-keyword">switch</span> (action.type) {
    <span class="hljs-keyword">case</span> ADD_TODO:
      <span class="hljs-keyword">return</span> [
        {
          id: state.reduce((maxId, todo) =&gt; <span class="hljs-built_in">Math</span>.max(todo.id, maxId), <span class="hljs-number">-1</span>) + <span class="hljs-number">1</span>,
          completed: <span class="hljs-literal">false</span>,
          text: action.text
        },
        ...state
      ]

    <span class="hljs-keyword">default</span>:
      <span class="hljs-keyword">return</span> state
  }
}
</code></pre>
<p>can be tested like:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> reducer <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;../../reducers/todos&apos;</span>
<span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> types <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;../../constants/ActionTypes&apos;</span>

describe(<span class="hljs-string">&apos;todos reducer&apos;</span>, () =&gt; {
  it(<span class="hljs-string">&apos;should return the initial state&apos;</span>, () =&gt; {
    expect(
      reducer(<span class="hljs-literal">undefined</span>, {})
    ).toEqual([
      {
        text: <span class="hljs-string">&apos;Use Redux&apos;</span>,
        completed: <span class="hljs-literal">false</span>,
        id: <span class="hljs-number">0</span>
      }
    ])
  })

  it(<span class="hljs-string">&apos;should handle ADD_TODO&apos;</span>, () =&gt; {
    expect(
      reducer([], {
        type: types.ADD_TODO,
        text: <span class="hljs-string">&apos;Run the tests&apos;</span>
      })
    ).toEqual(
      [
        {
          text: <span class="hljs-string">&apos;Run the tests&apos;</span>,
          completed: <span class="hljs-literal">false</span>,
          id: <span class="hljs-number">0</span>
        }
      ]
    )

    expect(
      reducer(
        [
          {
            text: <span class="hljs-string">&apos;Use Redux&apos;</span>,
            completed: <span class="hljs-literal">false</span>,
            id: <span class="hljs-number">0</span>
          }
        ],
        {
          type: types.ADD_TODO,
          text: <span class="hljs-string">&apos;Run the tests&apos;</span>
        }
      )
    ).toEqual(
      [
        {
          text: <span class="hljs-string">&apos;Run the tests&apos;</span>,
          completed: <span class="hljs-literal">false</span>,
          id: <span class="hljs-number">1</span>
        },
        {
          text: <span class="hljs-string">&apos;Use Redux&apos;</span>,
          completed: <span class="hljs-literal">false</span>,
          id: <span class="hljs-number">0</span>
        }
      ]
    )
  })
})
</code></pre>
<h3 id="components">Components</h3>
<p>A nice thing about React components is that they are usually small and only rely on their props. That makes them easy to test.</p>
<p>First, we will install <a href="http://airbnb.io/enzyme/" target="_blank">Enzyme</a>. Enzyme uses the <a href="https://facebook.github.io/react/docs/test-utils.html" target="_blank">React Test Utilities</a> underneath, but is more convenient, readable, and powerful.</p>
<pre><code>npm install --save-dev enzyme
</code></pre><p>To test the components we make a <code>setup()</code> helper that passes the stubbed callbacks as props and renders the component with <a href="http://airbnb.io/enzyme/docs/api/shallow.html" target="_blank">shallow rendering</a>. This lets individual tests assert on whether the callbacks were called when expected.</p>
<h4 id="example">Example</h4>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React, { PropTypes, Component } <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;react&apos;</span>
<span class="hljs-keyword">import</span> TodoTextInput <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;./TodoTextInput&apos;</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Header</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Component</span> </span>{
  handleSave(text) {
    <span class="hljs-keyword">if</span> (text.length !== <span class="hljs-number">0</span>) {
      <span class="hljs-keyword">this</span>.props.addTodo(text)
    }
  }

  render() {
    <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">header</span> <span class="hljs-attr">className</span>=<span class="hljs-string">&apos;header&apos;</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>todos<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">TodoTextInput</span> <span class="hljs-attr">newTodo</span>=<span class="hljs-string">{true}</span>
                         <span class="hljs-attr">onSave</span>=<span class="hljs-string">{this.handleSave.bind(this)}</span>
                         <span class="hljs-attr">placeholder</span>=<span class="hljs-string">&apos;What needs to be done?&apos;</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">header</span>&gt;</span>
    )
  }
}

Header.propTypes = {
  addTodo: PropTypes.func.isRequired
}

export default Header
</span></code></pre>
<p>can be tested like:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;react&apos;</span>
<span class="hljs-keyword">import</span> { shallow } <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;enzyme&apos;</span>
<span class="hljs-keyword">import</span> Header <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;../../components/Header&apos;</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">setup</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> props = {
    addTodo: jest.fn()
  }

  <span class="hljs-keyword">const</span> enzymeWrapper = shallow(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Header</span> {<span class="hljs-attr">...props</span>} /&gt;</span>)

  return {
    props,
    enzymeWrapper
  }
}

describe(&apos;components&apos;, () =&gt; {
  describe(&apos;Header&apos;, () =&gt; {
    it(&apos;should render self and subcomponents&apos;, () =&gt; {
      const { enzymeWrapper } = setup()

      expect(enzymeWrapper.find(&apos;header&apos;).hasClass(&apos;header&apos;)).toBe(true)

      expect(enzymeWrapper.find(&apos;h1&apos;).text()).toBe(&apos;todos&apos;)

      const todoInputProps = enzymeWrapper.find(&apos;TodoTextInput&apos;).props()
      expect(todoInputProps.newTodo).toBe(true)
      expect(todoInputProps.placeholder).toEqual(&apos;What needs to be done?&apos;)
    })

    it(&apos;should call addTodo if length of text is greater than 0&apos;, () =&gt; {
      const { enzymeWrapper, props } = setup()
      const input = enzymeWrapper.find(&apos;TodoTextInput&apos;)
      input.props().onSave(&apos;&apos;)
      expect(props.addTodo.mock.calls.length).toBe(0)
      input.props().onSave(&apos;Use Redux&apos;)
      expect(props.addTodo.mock.calls.length).toBe(1)
    })
  })
})
</span></code></pre>
<h3 id="connected-components">Connected Components</h3>
<p>If you use a library like <a href="https://github.com/reactjs/react-redux" target="_blank">React Redux</a>, you might be using <a href="https://medium.com/@dan_abramov/mixins-are-dead-long-live-higher-order-components-94a0d2f9e750" target="_blank">higher-order components</a> like <a href="https://github.com/reactjs/react-redux/blob/master/docs/api.md#connectmapstatetoprops-mapdispatchtoprops-mergeprops-options" target="_blank"><code>connect()</code></a>. This lets you inject Redux <a href="../Glossary.html#state" class="glossary-term" title="">state</a> into a regular React component.</p>
<p>Consider the following <code>App</code> component:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { connect } <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;react-redux&apos;</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">App</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Component</span> </span>{ <span class="hljs-comment">/* ... */</span> }

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> connect(mapStateToProps)(App)
</code></pre>
<p>In a unit test, you would normally import the <code>App</code> component like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> App <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;./App&apos;</span>
</code></pre>
<p>However, when you import it, you&apos;re actually holding the wrapper component returned by <code>connect()</code>, and not the <code>App</code> component itself. If you want to test its interaction with Redux, this is good news: you can wrap it in a <a href="https://github.com/reactjs/react-redux/blob/master/docs/api.md#provider-store" target="_blank"><code>&lt;Provider&gt;</code></a> with a <a href="../Glossary.html#store" class="glossary-term" title="">store</a> created specifically for this unit test. But sometimes you want to test just the rendering of the component, without a Redux <a href="../Glossary.html#store" class="glossary-term" title="">store</a>.</p>
<p>In order to be able to test the App component itself without having to deal with the decorator, we recommend you to also export the undecorated component:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { connect } <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;react-redux&apos;</span>

<span class="hljs-comment">// Use named export for unconnected component (for tests)</span>
<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">App</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Component</span> </span>{ <span class="hljs-comment">/* ... */</span> }

<span class="hljs-comment">// Use default export for the connected component (for app)</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> connect(mapStateToProps)(App)
</code></pre>
<p>Since the default export is still the decorated component, the import statement pictured above will work as before so you won&apos;t have to change your application code. However, you can now import the undecorated <code>App</code> components in your test file like this:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Note the curly braces: grab the named export instead of default export</span>
<span class="hljs-keyword">import</span> { App } <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;./App&apos;</span>
</code></pre>
<p>And if you need both:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> ConnectedApp, { App } <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;./App&apos;</span>
</code></pre>
<p>In the app itself, you would still import it normally:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> App <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;./App&apos;</span>
</code></pre>
<p>You would only use the named export for tests.</p>
<blockquote>
<h5 id="a-note-on-mixing-es6-modules-and-commonjs">A Note on Mixing ES6 Modules and CommonJS</h5>
<p>If you are using ES6 in your application source, but write your tests in ES5, you should know that Babel handles the interchangeable use of ES6 <code>import</code> and CommonJS <code>require</code> through its <a href="http://babeljs.io/docs/usage/modules/#interop" target="_blank">interop</a> capability to run two module formats side-by-side, but the behavior is <a href="https://github.com/babel/babel/issues/2047" target="_blank">slightly different</a>. If you add a second export beside your default export, you can no longer import the default using <code>require(&apos;./App&apos;)</code>. Instead you have to use <code>require(&apos;./App&apos;).default</code>.</p>
</blockquote>
<h3 id="middleware">Middleware</h3>
<p><a href="../Glossary.html#middleware" class="glossary-term" title="">Middleware</a> functions wrap behavior of <code>dispatch</code> calls in Redux, so to test this modified behavior we need to mock the behavior of the <code>dispatch</code> call.</p>
<h4 id="example">Example</h4>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> types <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;../../constants/ActionTypes&apos;</span>
<span class="hljs-keyword">import</span> singleDispatch <span class="hljs-keyword">from</span> <span class="hljs-string">&apos;../../middleware/singleDispatch&apos;</span>

<span class="hljs-keyword">const</span> createFakeStore = fakeData =&gt; ({
  getState() {
    <span class="hljs-keyword">return</span> fakeData
  }
})

<span class="hljs-keyword">const</span> dispatchWithStoreOf = (storeData, action) =&gt; {
  <span class="hljs-keyword">let</span> dispatched = <span class="hljs-literal">null</span>
  <span class="hljs-keyword">const</span> dispatch = singleDispatch(createFakeStore(storeData))(actionAttempt =&gt; dispatched = actionAttempt)
  dispatch(action)
  <span class="hljs-keyword">return</span> dispatched
}

describe(<span class="hljs-string">&apos;middleware&apos;</span>, () =&gt; {
  it(<span class="hljs-string">&apos;should dispatch if store is empty&apos;</span>, () =&gt; {
    <span class="hljs-keyword">const</span> action = {
      type: types.ADD_TODO
    }

    expect(
      dispatchWithStoreOf({}, action)
    ).toEqual(action)
  })

  it(<span class="hljs-string">&apos;should not dispatch if store already has type&apos;</span>, () =&gt; {
    <span class="hljs-keyword">const</span> action = {
      type: types.ADD_TODO
    }

    expect(
      dispatchWithStoreOf({
        [types.ADD_TODO]: <span class="hljs-string">&apos;dispatched&apos;</span>
      }, action)
    ).toNotExist()
  })
})
</code></pre>
<h3 id="glossary">Glossary</h3>
<ul>
<li><p><a href="http://airbnb.io/enzyme/" target="_blank">Enzyme</a>: Enzyme is a JavaScript Testing utility for React that makes it easier to assert, manipulate, and traverse your React Components&apos; output.</p>
</li>
<li><p><a href="http://facebook.github.io/react/docs/test-utils.html" target="_blank">React Test Utils</a>: Test Utilities for React. Used by Enzyme.</p>
</li>
<li><p><a href="http://airbnb.io/enzyme/docs/api/shallow.html" target="_blank">Shallow rendering</a>: Shallow rendering lets you instantiate a component and effectively get the result of its <code>render</code> method just a single level deep instead of rendering components recursively to a DOM. Shallow rendering is useful for unit tests, where you test a particular component only, and importantly not its children. This also means that changing a child component won&apos;t affect the tests for the parent component. Testing a component and all its children can be accomplished with <a href="http://airbnb.io/enzyme/docs/api/mount.html" target="_blank">Enzyme&apos;s <code>mount()</code> method</a>, aka full DOM rendering.</p>
</li>
</ul>

                                
                                </section>
                            
    </div>
    <div class="search-results">
        <div class="has-results">
            
            <h1 class="search-results-title"><span class='search-results-count'></span> results matching "<span class='search-query'></span>"</h1>
            <ul class="search-results-list"></ul>
            
        </div>
        <div class="no-results">
            
            <h1 class="search-results-title">No results matching "<span class='search-query'></span>"</h1>
            
        </div>
    </div>
</div>

                        </div>
                    </div>
                
            </div>

            
                
                <a href="ServerRendering.html" class="navigation navigation-prev " aria-label="Previous page: Server Rendering">
                    <i class="fa fa-angle-left"></i>
                </a>
                
                
                <a href="ComputingDerivedData.html" class="navigation navigation-next " aria-label="Next page: Computing Derived Data">
                    <i class="fa fa-angle-right"></i>
                </a>
                
            
        
    </div>

    <script>
        var gitbook = gitbook || [];
        gitbook.push(function() {
            gitbook.page.hasChanged({"page":{"title":"Writing Tests","level":"1.5.5","depth":2,"next":{"title":"Computing Derived Data","level":"1.5.6","depth":2,"path":"recipes/ComputingDerivedData.md","ref":"./recipes/ComputingDerivedData.md","articles":[]},"previous":{"title":"Server Rendering","level":"1.5.4","depth":2,"path":"recipes/ServerRendering.md","ref":"./recipes/ServerRendering.md","articles":[]},"dir":"ltr"},"config":{"gitbook":"*","theme":"default","variables":{},"plugins":["livereload"],"pluginsConfig":{"livereload":{},"highlight":{},"search":{},"lunr":{"maxIndexSize":1000000,"ignoreSpecialCharacters":false},"sharing":{"facebook":true,"twitter":true,"google":false,"weibo":false,"instapaper":false,"vk":false,"all":["facebook","google","twitter","weibo","instapaper"]},"fontsettings":{"theme":"white","family":"sans","size":2},"theme-default":{"styles":{"website":"styles/website.css","pdf":"styles/pdf.css","epub":"styles/epub.css","mobi":"styles/mobi.css","ebook":"styles/ebook.css","print":"styles/print.css"},"showLevel":false}},"structure":{"langs":"LANGS.md","readme":"README.md","glossary":"GLOSSARY.md","summary":"SUMMARY.md"},"pdf":{"pageNumbers":true,"fontSize":12,"fontFamily":"Arial","paperSize":"a4","chapterMark":"pagebreak","pageBreaksBefore":"/","margin":{"right":62,"left":62,"top":56,"bottom":56}},"styles":{"website":"styles/website.css","pdf":"styles/pdf.css","epub":"styles/epub.css","mobi":"styles/mobi.css","ebook":"styles/ebook.css","print":"styles/print.css"}},"file":{"path":"recipes/WritingTests.md","mtime":"2017-03-13T14:28:11.351Z","type":"markdown"},"gitbook":{"version":"3.2.2","time":"2017-03-15T14:47:19.389Z"},"basePath":"..","book":{"language":""}});
        });
    </script>
</div>

        
    <script src="../gitbook/gitbook.js"></script>
    <script src="../gitbook/theme.js"></script>
    
        
        <script src="../gitbook/gitbook-plugin-livereload/plugin.js"></script>
        
    
        
        <script src="../gitbook/gitbook-plugin-search/search-engine.js"></script>
        
    
        
        <script src="../gitbook/gitbook-plugin-search/search.js"></script>
        
    
        
        <script src="../gitbook/gitbook-plugin-lunr/lunr.min.js"></script>
        
    
        
        <script src="../gitbook/gitbook-plugin-lunr/search-lunr.js"></script>
        
    
        
        <script src="../gitbook/gitbook-plugin-sharing/buttons.js"></script>
        
    
        
        <script src="../gitbook/gitbook-plugin-fontsettings/fontsettings.js"></script>
        
    

    </body>
</html>

